<template>
  <div class="app-container">

    <!-- 查询操作 -->
    <el-form :inline="true" class="filter-container filter">
      <el-form-item label="团队名称">
        <el-input v-model="listQuery.fteamname" clearable class="filter-item" style="width: 200px;"
          placeholder="请输入团队名称" />
      </el-form-item>
      <el-form-item>
        <el-button round size="medium" class="filter-item"
          :style="{ background: buttonColor.lookup, color: buttonColor.color }" @click="handleFilter">查找</el-button>
        <el-button round size="medium" class="filter-item"
          :style="{ background: buttonColor.add, color: buttonColor.color }" @click="handleCreate">添加</el-button>
      </el-form-item>
    </el-form>

    <!-- 查询结果 -->
    <el-table :height="buttonColor.clientHeight" v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。"
      border fit highlight-current-row :header-cell-style="tableColor">
      <el-table-column align="center" :width="buttonColor.operationTwo" label="操作" class-name="small-padding">
        <template slot-scope="scope">
          <div class="operationButton">
            <div :style="{ color: buttonColor.edit, cursor: 'pointer' }" @click="handleUpdate(scope.row)">
              <img src="../../../public/images/edit.png" />
              编辑
            </div>
            <div :style="{ color: buttonColor.delete, cursor: 'pointer' }" @click="handleDelete(scope.row)">
              <img src="../../../public/images/del.png" />
              删除
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column :width="buttonColor.line" :index="indexMethod" align="center" label="序" type="index" />
      <el-table-column :width="buttonColor.name" align="left" label="团队编号" prop="fteamno" />
      <el-table-column width="200" align="left" label="团队名称" prop="fteamname" />
      <el-table-column :formatter="fpersonFormatter" align="left" label="负责人" prop="fperson" />
      <el-table-column align="left" :width="buttonColor.state" label="状态" prop="fstate">
        <template slot-scope="scope">
          <span :style="{ color: buttonColor.statedisable }" v-if="scope.row.fstate === 0">{{
              scope.row.fstate | statusFilter
          }}</span>
          <span :style="{ color: buttonColor.statestart }" v-else>{{ scope.row.fstate | statusFilter }}</span>
        </template>
      </el-table-column>

    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
      @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog width="auto" top="0vh" :close-on-click-modal="false" :visible.sync="dialogFormVisible">
      <template slot="title">
        <div :style="titleColor">{{ textMap[dialogStatus] }}</div>
      </template>
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="auto">
        <el-row>
          <el-col :span="12">
            <el-form-item class="required" label="团队编号" prop="fteamno">
              <el-input v-if="dialogStatus=='create'" v-model="dataForm.fteamno" />
              <el-input v-else disabled v-model="dataForm.fteamno" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="required" label="状态" prop="attribute">
              <el-select v-model="dataForm.fstate" clearable filterable class="filter-item" placeholder="请选择状态">
                <el-option v-for="item in fstateList" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
              <el-form-item class="required" label="团队名称" prop="fteamname">
                <el-input v-model="dataForm.fteamname" />
              </el-form-item>
          </el-col>
          <el-col :span="12">

            <el-form-item class="searchOne required" label="责任人" prop="fperson">
              <div style="display:flex;justify-content:flex-start;align-items:center">
                <el-select style="display: inline-block" clearable filterable v-model="dataForm.fperson"
                  class="filter-item" placeholder="请选择责任人">
                  <el-option v-for="item in getListforduserAdd" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
                <i class="el-icon-search selectI" @click="searchDialoguse('add')" />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item style="width: 100% !important" class="text" label="备注" prop="fmemo">
              <el-input v-model="dataForm.fmemo" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button round :style="{ background: buttonColor.cancel, color: buttonColor.colorone }"
          @click="dialogFormVisible = false">取消</el-button>
        <el-button round v-if="dialogStatus == 'create'"
          :style="{ background: buttonColor.confirm, color: buttonColor.color }" @click="createData">确定</el-button>
        <el-button round v-else :style="{ background: buttonColor.confirm, color: buttonColor.color }"
          @click="updateData">确定
        </el-button>
      </div>
    </el-dialog>

    <userDialog :searchVisibleuse.sync="searchVisibleuse" :fsiteNo.sync="userDialogFsiteNo" :tableColor="tableColor"
      @userDialog="userDialogValue" />
  </div>
</template>

<style>
.button-margin {
  margin: 2px 0px;
}

.el-button+.el-button {
  margin-left: 1px;
}
</style>

<script>
/**
 * 引入api
 * 引入组件
 */
import { listtsTeam, createtsTeam, updatetsTeam, deletetsTeam } from '@/api/labOrder/team'
import { getListArea } from '@/api/area'
import UserDialog from '@/components/UserDialog'
import Pagination from '@/components/Pagination'
import { tableColor, titleColor, buttonColor } from '@/filters/index'
import moment from 'moment'

const statusMap = {
  0: '停用',
  1: '正常'
}

export default {
  name: 'WTeam',
  // 使用组件
  components: { Pagination, UserDialog },
  // 表单状态过滤
  filters: {
    statusFilter(type) {
      return statusMap[type]
    }
  },
  data() {
    return {
      userFlag: null, // 判断人员是搜索还是添加
      searchVisibleuse: false, // 是否显示人员弹窗
      userDialogFsiteNo: null, // 客户编号(人员弹出框)
      getListforduserAdd: [], // 添加人员列表
      fstateList: [
        { label: '正常', value: 1},
        { label: '停用', value: 0},
      ],
      tableColor, // 表格颜色
      titleColor, // 弹窗颜色
      buttonColor, // 按钮颜色
      list: null, // 查询表单数据
      total: 0, // 表单总条数
      listLoading: true, // 等待查询loading
      listQuery: { // 查询字段
        page: 1,
        limit: 20,
        fsiteNo: undefined,
        fteamname: undefined,
        sort: 'create_time',
        order: 'desc'
      },
      dataForm: { // 添加，编辑字段
        fteamno: undefined,
        fteamname: undefined,
        fsiteNo: undefined,
        fperson: undefined,
        fmemo: undefined,
        fstate: undefined,
        id: undefined
      },
      dialogFormVisible: false, // 添加，编辑弹窗是否显示
      dialogStatus: '', // 判断弹窗是添加/编辑
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: { // 表单提交规则
        fteamno: [
          { required: true, message: '团队编号不能为空' },
        ],
        fteamname: [
          { required: true, message: '团队名称不能为空' },
        ],
        fperson: [
          { required: true, message: '责任人不能为空' },
        ],
      }
    }
  },
  created() {
    this.getList()
    this.listQuery.fsiteNo = this.$store.state.user.fsiteNo;
    getListArea({ flag: 13, arg1: this.$store.state.user.fsiteNo })
        .then(response => {
          this.getListforduserAdd = response.data.data.list
        })
        .catch(() => {
          this.getListforduserAdd = []
        })
  },
  methods: {
    // 搜索人员弹出框
    searchDialoguse(value) {
      this.userFlag = value
      if (value === 'add') {
        this.userDialogFsiteNo = this.listQuery.fsiteNo
      } else {
        this.userDialogFsiteNo = this.listQuery.fsiteNo
      }
      this.searchVisibleuse = true
    },

    // 人员弹出框返回值
    userDialogValue(value) {
      if (this.userFlag === 'add') {
        this.dataForm.fperson = value.user.id.toString()
      } else {
        this.listQuery.fperson = value.user.id.toString()
      }
    },
    // 人员回显
    fpersonFormatter: function (row, column) {
      if (this.getListforduserAdd) {
        for (let i = 0; i < this.getListforduserAdd.length; i++) {
          if (row.fperson == this.getListforduserAdd[i].value) {
            return this.getListforduserAdd[i].label
          }
        }
        return ''
      } else {
        return ''
      }
    },
    // 时间回显
    datetimeFormat(row, column) {
      const date = row[column.property]
      if (date === undefined || date === null) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD HH:mm:ss')
    },
    // 获取数据
    getList() {
      this.listLoading = true
      listtsTeam(this.listQuery)
        .then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    // 查找
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 添加时重置表单
    resetForm() {
      this.dataForm = {
        fteamno: undefined,
        fteamname: undefined,
        fsiteNo: undefined,
        fperson: undefined,
        fmemo: undefined,
        fstate: undefined,
        id: undefined
      }
    },
    // 打开添加弹窗
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.dataForm.fstate = 1
      this.dataForm.fsiteNo = this.$store.state.user.fsiteNo;
      this.dataForm.fperson = this.$store.state.user.id.toString()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 添加
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createtsTeam(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '添加团队成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.data
              })
            })
        }
      })
    },
    // 打开编辑弹窗
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 编辑
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updatetsTeam(this.dataForm, this.$route.query.id)
            .then(() => {
              for (const v of this.list) {
                if (v.fteamno === this.dataForm.fteamno) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新团队成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.data
              })
            })
        }
      })
    },
    // 删除
    handleDelete(row) {
      this.$confirm('是否要删除团队', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletetsTeam(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除团队成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.data
            })
          })
      })
    },
    // 表单序号
    indexMethod(index) {
      index = index + 1
      return index
    }
  }
}
</script>
